import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio,Switch, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import CryptoJS from 'crypto-js';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  parentId: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues,parentId } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.image_file_id   = picture[0].file_id
        fieldsValue.image_file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      fieldsValue.parent_id = parentId;
      console.log("submit fields ", fieldsValue)
      fieldsValue.type = 1;
      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues?.image_file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)

  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={isUpdate?'编辑':'新增'}
    width={"40%"}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'表情符号'}>
      {form.getFieldDecorator('code', {
        initialValue: isUpdate ? dataFormValues.code : '',
        rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) }],
      })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'表情图片'}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={isUpdate?defaultPicture:[]}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ table_type:4, table_name: 'emojis', }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => { setPreviewImg(dataFormValues?.image_file_url) ;handlePreviewModalVisible(true)}}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否启用'>
      {form.getFieldDecorator('is_enable', {
        initialValue: isUpdate ? dataFormValues.is_enable : false,
        valuePropName: 'checked',
        // rules: [],
      })(<Switch  />)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.rank_num' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 888,
        // rules: [],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} min={1}/>)}
    </FormItem>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
